<template>
  <view class="container">
        <view class="top"></view>
        <view class="bottomStart">
            <view class="controlParent">
                <view class="control">
                    <view class="dizuo">
                        <view
                            class="yaogan"
                            @tap="onHandleTap"
                            @touchmove="bindtouchmove"
                            @touchend="bindtouchend"
                            @touchcancel="bindtouchend"
                            :style="'transform: rotate(' + (rotateDeg + '') + 'deg);'"
                        >
                            <image src="https://goverment-cdn.oss-cn-hangzhou.aliyuncs.com/assets/yaogan%403x.png" class="controlImage" mode="aspectFit" />
                        </view>
                        <image src="https://goverment-cdn.oss-cn-hangzhou.aliyuncs.com/assets/dizuo%403x.png" class="controlBottom" mode="aspectFit" />
                        <image src="https://goverment-cdn.oss-cn-hangzhou.aliyuncs.com/assets/qiu%403x.png" class="controlBall" mode="aspectFit" />
                    </view>
                </view>
            </view>
            <view class="gameState">
                <view class="gameCount" v-if="!hasPrizes">
                    <text>剩余{{ surplus || 0 }}次机会</text>
                </view>
                <view class="loading" v-if="loading">
                    <image src="https://goverment-cdn.oss-cn-hangzhou.aliyuncs.com/assets/c%403x.png" mode="aspectFit" class="loadingImage1" />
                </view>
                <view class="prizes" v-if="hasPrizes">
                    <text class="prizesTitle">中奖编号：{{ prizesCode }}</text>
                    <text class="prizesDesc">恭喜您获得奖品一份</text>
                </view>
            </view>
        </view>
        <view :class="'modal ' + (modalHidden ? 'hidden' : '')">
            <view class="modal-musk"></view>
            <view class="modal-content">
                <view class="topTips">
                    <image v-if="hasPrizes" src="https://goverment-cdn.oss-cn-hangzhou.aliyuncs.com/assets/prize.png" class="noprize-image" mode="aspectFit" />
                    <image v-else src="https://goverment-cdn.oss-cn-hangzhou.aliyuncs.com/assets/noprize.png" class="prize-image" mode="aspectFit" />
                    <view v-if="hasPrizes" class="prize-content">
                        <text>获得奖品一份！</text>
                        <image src="https://goverment-cdn.oss-cn-hangzhou.aliyuncs.com/assets/yu%201.png" class="prizeImage1" mode="" />
                        <image src="https://goverment-cdn.oss-cn-hangzhou.aliyuncs.com/assets/yu%201.png" class="prizeImage2" mode="" />
                    </view>
                    <view v-else class="noprize-content">
                        <image src="https://goverment-cdn.oss-cn-hangzhou.aliyuncs.com/assets/emoji.png" mode="" />
                        <text class="noprize-text">剩余{{ surplus }}次机会</text>
                    </view>
                </view>
                <view class="bottomBtn" v-if="hasPrizes">
                    <button @tap="fillQuestionnaire">填写问卷</button>
                </view>
                <view class="bottomBtn" v-else>
                    <button @tap="confirm">{{ surplus <= 0 ? '填写问卷' : '知道了' }}</button>
                </view>
            </view>
        </view>
        <view :class="'modal tipsModal ' + (!showErrorModal ? 'hidden' : '')">
            <view class="modal-musk"></view>
            <view class="modal-content">
                <view class="topTips">
                    <text>{{ errorMessage }}</text>
                </view>
                <view class="bottomBtn">
                    <button @tap="retry">重试</button>
                </view>
            </view>
        </view>
    </view>
</template>
<script lang="ts">
import { userLogin } from "@/services/utils";
// index.ts
// 获取应用实例
const app = getApp();
let defaultTouchX = 0;
let defaultTouchY = 0;
let canDrag = true;
enum RegisterStatusResponseDataTypeCodeEnum {
    SUCCESS,
    ALERADY,
    OTHERINGAME,
    MAX_PLAYED,
    HAS_PRIZED,
    HOST_OFFLINE
}
export default {
    data() {
        return {
            motto: 'Hello World',
            userInfo: {},
            showErrorModal: false,
            errorMessage: '游戏注册失败，请重试',
            hasUserInfo: false,
            modalHidden: true,
            hasPrizes: false,
            // 中奖状态
            prizesCode: '-1',
            surplus: 0,
            rotateDeg: 15,
            loading: false,
            canStart: false,
            canIUse: uni.canIUse('button.open-type.getUserInfo'),
            canIUseGetUserProfile: false,
            canIUseOpenData: false // 如需尝试获取用户信息可改为false
        };
    },
    onLoad() {
        const paramsDeviceId = this.getParam()['device'];
        if (paramsDeviceId) {
          uni.setStorageSync('DEVICE_ID_PARAMS', paramsDeviceId);
        }
        this.runLogin();
    },
    methods: {
        // 事件处理函数
        setData(datas) { 
          Object.keys(datas).map(item => {
            this[item] = datas[item]
          })
        },

        getPrizesId(id: number) {
            const strNum = id + '';
            switch (strNum.length) {
                case 1:
                    return '00' + strNum;
                case 2:
                    return '0' + strNum;
                default:
                    return strNum;
            }
        },

        confirm() {
            if (this.hasPrizes || this.surplus <= 0) {
              uni.reLaunch({
                  url: '/packageTokaeGame/form/form?device=' + this.getDeviceId()
              });
            } else {
                this.setData({
                    modalHidden: true
                });
            }
        },

        getDeviceId() {
          const storageId = uni.getStorageSync('DEVICE_ID_PARAMS');
          if (storageId) {
            return storageId;
          }
          return 1;
        },

        getGameState(start?: boolean) {
            const token = uni.getStorageSync('tokae_token');
            const device = this.getDeviceId();
            uni.request({
                url: process.env.CLOUD_URL + '/game/getUserGameState?_=' + Date.now(),
                method: 'GET',
                header: {
                    authorization: token,
                    device
                },
                success: (res: any) => {
                    const response = res.data;
                    if (response) {
                        this.setData({
                            hasPrizes: response.hasPrizes,
                            prizesCode: this.getPrizesId(response.prizesId),
                            surplus: response.surplus
                        });
                        if (response.hasPrizes) {
                            uni.hideLoading();
                            this.setData({
                                canStart: false,
                                modalHidden: false
                            });
                        } else if (response.surplus <= 0) {
                            uni.hideLoading();
                            this.setData({
                                canStart: false,
                                modalHidden: false
                            });
                        } else {
                            this.register().then(() => {
                                if (start) {
                                    this.pushTask();
                                }
                            });
                        }
                    } else {
                        uni.hideLoading();
                    }
                    if (res.statusCode === 401) {
                        this.handleLogin();
                    }
                },
                fail: (err: any): void => {
                    uni.showToast({
                        icon: 'error',
                        title: '游戏注册失败',
                        duration: 3000
                    });
                    uni.hideLoading();
                    console.log(err);
                }
            });
        },

        retry() {
            uni.showLoading({
                title: '正在加载'
            });
            this.setData({
                showErrorModal: false
            });
            this.register();
        },

        register() {
            const token = uni.getStorageSync('tokae_token');
            const device = this.getDeviceId();
            return new Promise((resolve, reject) => {
                uni.request({
                    url: process.env.CLOUD_URL + '/game/register',
                    method: 'POST',
                    header: {
                        authorization: token,
                        device
                    },
                    success: (res: any) => {
                        uni.hideLoading();
                        if (res.data && res.data.code !== undefined) {
                            const code: RegisterStatusResponseDataTypeCodeEnum = res.data.code;
                            switch (code) {
                                case RegisterStatusResponseDataTypeCodeEnum.ALERADY:
                                case RegisterStatusResponseDataTypeCodeEnum.SUCCESS:
                                case RegisterStatusResponseDataTypeCodeEnum.HAS_PRIZED: {
                                    this.setData({
                                        canStart: true
                                    });
                                    resolve(res);
                                    break;
                                }
                                case RegisterStatusResponseDataTypeCodeEnum.HOST_OFFLINE:
                                case RegisterStatusResponseDataTypeCodeEnum.OTHERINGAME: {
                                    this.setData({
                                        showErrorModal: true,
                                        errorMessage: res.data.message || '游戏注册失败，请重试'
                                    });
                                    reject();
                                    break;
                                }
                                case RegisterStatusResponseDataTypeCodeEnum.MAX_PLAYED: {
                                    this.setData({
                                        modalHidden: false,
                                        surplus: 0,
                                        hasPrizes: false
                                    });
                                    reject();
                                    break;
                                }
                            }
                        } else {
                            this.setData({
                                showErrorModal: true,
                                errorMessage: res.data.message || '游戏注册失败，请重试'
                            });
                        }
                    },
                    fail: (err: any): void => {
                        this.setData({
                            showErrorModal: true,
                            errorMessage: '游戏注册失败，请重试'
                        });
                        uni.hideLoading();
                        reject();
                    }
                });
            });
        },

        pushTask() {
            const token = uni.getStorageSync('tokae_token');
            const device = this.getDeviceId();
            this.register().then(() => {
                uni.request({
                    url: process.env.CLOUD_URL + '/game/pushTask',
                    method: 'POST',
                    header: {
                        authorization: token,
                        device
                    },
                    success: (res: any) => {
                        if (res.data && (res.data.code === 0 || res.data.code === 1)) {
                            this.setData({
                                loading: true
                            });
                            this.startFetchGameState();
                        }
                        if (res.statusCode === 401) {
                            this.handleLogin();
                        }
                    },
                    fail: (err: any): void => {}
                });
            });
        },

        onHandleTap(e: any) {
            // canDrag = false;
            // if (!this.data.hasPrizes) {
            //     this.getGameState(true);
            // } else {
            //     wx.showToast({
            //         icon: 'error',
            //         title: '您已中奖',
            //         duration: 3000
            //     });
            // }
        },

        bindtouchmove(e: any) {
            if (!canDrag) {
                return;
            }
            if (!this.canStart) {
                return;
            }
            const rotateDeg = this.rotateDeg;
            let result = rotateDeg;
            if (e.changedTouches) {
                if (e.changedTouches[0].pageX > defaultTouchX) {
                    result += 1;
                } else {
                    result -= 1;
                }
                if (e.changedTouches[0].pageY > defaultTouchY) {
                    result += 1;
                } else {
                    result -= 1;
                }
                defaultTouchX = e.changedTouches[0].pageX;
                defaultTouchY = e.changedTouches[0].pageY;
                result = result > 75 ? 75 : result < 15 ? 15 : result;
                this.setData({
                    rotateDeg: result
                });
                if (result >= 75) {
                    canDrag = false;
                    if (!this.hasPrizes) {
                        this.getGameState(true);
                    } else {
                        uni.showToast({
                            icon: 'error',
                            title: '您已中奖',
                            duration: 3000
                        });
                    }
                }
            }
        },

        bindtouchend(e: any) {
            if (this.rotateDeg < 75) {
                this.setData({
                    rotateDeg: 75
                });
                canDrag = false;
                if (!this.hasPrizes) {
                    this.getGameState(true);
                } else {
                    uni.showToast({
                        icon: 'error',
                        title: '您已中奖',
                        duration: 3000
                    });
                }
            }
        },
        getParam(){
          let routes: { route: string, options?: { [key: string]: string } }[] = getCurrentPages(); // 获取当前打开过的页面路由数组
          let curParam = routes[routes.length - 1].options; //获取路由参数
          // 拼接参数
          return curParam
        },

        startFetchGameState() {
            const token = uni.getStorageSync('tokae_token');
            const device = this.getDeviceId();
            uni.request({
                url: process.env.CLOUD_URL + '/game/pollMobile?_=' + Date.now(),
                method: 'GET',
                header: {
                    authorization: token,
                    device
                },
                success: (res: any) => {
                    const game = res.data.game;
                    if (!game) {
                        return;
                    }
                    if (game.code !== 0) {
                        canDrag = true;
                        this.setData({
                            rotateDeg: 15,
                            loading: false
                        });
                    }
                    if (game.code === 0) {
                        console.log('正在运行');
                        setTimeout(() => {
                            this.startFetchGameState();
                        }, 2000);
                    } else if (game.code === 1) {
                        console.log('运行结束');
                        this.setData({
                            hasPrizes: game.data.hasPrizes,
                            prizesCode: this.getPrizesId(game.data.prizesId),
                            modalHidden: false,
                            surplus: game.data.surplus
                        });
                    } else if (game.code === -1 || game.code === -2) {
                        uni.showToast({
                            icon: 'error',
                            title: '查询错误',
                            duration: 3000
                        });
                    } else {
                        uni.showToast({
                            icon: 'error',
                            title: '查询错误',
                            duration: 3000
                        });
                    }
                    if (res.statusCode === 401) {
                        this.handleLogin();
                    }
                },
                fail: (err: any): void => {
                    uni.showToast({
                        icon: 'error',
                        title: '查询错误',
                        duration: 3000
                    });
                }
            });
        },

        fillQuestionnaire() {
            uni.reLaunch({
                url: '/packageTokaeGame/form/form?device=' + this.getDeviceId()
            });
        },

        handleLogin() {
            // 接口请求失败了，尝试重新登录
            console.log('接口请求失败了，尝试重新登录');
            this.runLogin();
        },

        registerUser() {
          return new Promise((resolve, reject) => {
            try {
              const loginParam: { type: number, code?: string } = {
                type: 1,
              };
              if (!uni.getStorageSync("OPENID")) {
                uni.login({
                  provider: "weixin",
                  success: async (res) => {
                    console.log(res);
                    loginParam.code = res.code;
                    const { data } = await userLogin(loginParam);
                    uni.setStorageSync("OPENID", data?.openId);
                    uni.setStorageSync("UNIONID", data?.unionId);
                    uni.setStorageSync("TOKEN", data?.accessToken);
                    resolve(res);
                  },
                  fail: (e) => {
                    reject(e)
                  }
                });
              } else {
                resolve(loginParam);
              }
            } catch (e) {
              reject(e);
            }
          })
        },

        async runLogin() {
          try {
            await this.registerUser()
          } catch (e) {
            uni.showToast({
              icon: 'error',
              title: '游戏注册失败',
              duration: 3000
            });
          }

          uni.showLoading({
              title: '正在加载'
          });
          const userPhone = getApp().globalData.user.phone;
          
          if (userPhone) {
            // 是会员
            getApp().getUserInfo().then((user) => {
              const memberid = user.memberScore.memberId;
              this.loginByMemberId(memberid);
            }).catch((e) => {
              uni.showToast({
                icon: 'error',
                title: '游戏注册失败',
                duration: 3000
              });
            });
          } else {
            // 不是会员
            getApp().getWechatUserProfile({
              path: '/packageTokaeGame/index/index?device=' + this.getDeviceId(),
              redirect: true
            })
          }
        },

        loginByMemberId(memberId: string) {
          return new Promise((resolve, reject) => {
            const device = this.getDeviceId();
            uni.request({
              method: 'POST',
              url: process.env.CLOUD_URL + '/user/loginByKaiJie',
              header: {
                device
              },
              data: {
                memberid: memberId
              },
              success: (res) => {
                  const result: any = res.data;
                  if (result) {
                      uni.setStorageSync('tokae_userInfo', result);
                      uni.setStorageSync('tokae_token', result.token);
                      this.getGameState();
                      resolve(result);
                  } else {
                      reject();
                  }
              },
              fail: () => {
                  uni.showToast({
                      icon: 'error',
                      title: '游戏注册失败',
                      duration: 3000
                  });
                  reject();
              }
            });
          })
        },
    }
};
</script>
<style>
/**index.wxss**/

page {
    height: 100%;
}
.container {
    flex: 1;
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: space-between;
  /* padding: 200rpx 0; */
  box-sizing: border-box;
  background:#3898FF url('https://goverment-cdn.oss-cn-hangzhou.aliyuncs.com/assets/00%2010%403x.png') center center no-repeat;
  background-size: cover;
  background-clip: contain;
} 
.container {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    overflow: hidden;
}
.top {
    flex: 1;
    flex-shrink: 0;
    width: 100%;
}
.bottomStart {
    width: 100%;
    flex: 1;
    flex-shrink: 0;
    display: flex;
    flex-direction: column;
    align-items: center;
    position: relative;
    bottom: -220rpx;
}
.controlParent {
    position: relative;
    width: 320rpx;
}
.centerImage {
    overflow: visible;
}
.control .controlImage {
    width: 126rpx;
    height: 290rpx;
}
.controlMusk {
    position: absolute;
    z-index: 3;
    left: -50px;
    top: -50px;
    right: -50px;
    bottom: -50px;
}
.dizuo {
    width: 324rpx;
    height: 182rpx;
    display: flex;
    justify-content: center;
}
.yaogan {
    position: absolute;
    top: -270rpx;
    transform-origin: bottom center;
    transform: rotate(70deg);
    z-index: 3;
    transition: all 0.1s;
}
.controlBottom {
    position: absolute;
    width: 324rpx;
    height: 182rpx;
    z-index: 2;
}
.controlBall {
    position: relative;
    z-index: 4;
    width: 128rpx;
    height: 92rpx;
}
.centerImage image {
    height: 200rpx;
    position: relative;
    top: 17vh;
}
.centerImag image {
    width: 100%;
}

.gameState .gameCount {
    text-align: center;
    font-family: Source Han Sans CN;
    font-size: 14px;
    font-weight: normal;
    text-align: center;
    letter-spacing: 0em;
    color: #c7d4ff;
    margin-top: 24rpx;
    /* margin-top: 100rpx; */
}
.gameState .loading {
    margin-top: 66rpx;
}
.gameState .loading .loadingImage1 {
    width: 536rpx;
    height: 128rpx;
}

.prizes {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    margin-top: 74rpx;
}
.prizes .prizesTitle {
    font-family: Source Han Sans CN;
    font-size: 24px;
    font-weight: bold;
    text-align: center;
    letter-spacing: 0em;

    color: #ffffff;
}
.prizes .prizesDesc {
    font-family: Source Han Sans CN;
    font-size: 14px;
    font-weight: normal;
    text-align: center;
    letter-spacing: 0em;
    margin-top: 24rpx;
    color: #ffffff;
}

.modal {
    position: fixed;
    left: 0;
    top: 0;
    bottom: 0;
    right: 0;
    display: flex;
    justify-content: center;
    align-items: center;
    z-index: 100;
}
.modal.hidden {
    display: none;
}
.modal .modal-musk {
    background-color: rgba(0, 0, 0, 0.5);
    position: absolute;
    left: 0;
    top: 0;
    bottom: 0;
    right: 0;
    opacity: 1;
    transition: all 11s;
}
.modal.hidden .modal-musk {
    opacity: 0;
    transition: all 11s;
}
.modal .modal-content {
    width: 600rpx;
    height: 600rpx;
    background: #64a2ff;
    position: relative;
    z-index: 4;
    border-radius: 40rpx;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    align-items: center;
    background: url('https://goverment-cdn.oss-cn-hangzhou.aliyuncs.com/assets/tcc%403x.png');
    background-size: cover;
    background-clip: contain;
}
.tipsModal .modal-content {
    height: 400rpx;
    background: linear-gradient(0deg, #64a2ff 0%, #0968f7 100%);
}
.modal .modal-content .topTips {
    padding-top: 50rpx;
    width: 100%;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
}
.tipsModal .modal-content .topTips {
    flex: 1;
    padding-bottom: 60rpx;
}
.tipsModal .modal-content .topTips text {
    font-family: Source Han Sans CN;
    font-size: 18px;
    font-weight: 500;
    letter-spacing: 0em;

    color: #ffffff;
}
.modal .modal-content .topTips .noprize-image,
.modal .modal-content .topTips .prize-image {
    height: 84rpx;
    width: 448rpx;
}
.modal .modal-content .topTips .noprize-content {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    margin-top: 32rpx;
}
.modal .modal-content .topTips .noprize-content image {
    width: 124rpx;
    height: 124rpx;
}
.modal .modal-content .topTips .noprize-content .noprize-text {
    font-size: 16px;
    font-weight: normal;
    text-align: center;
    letter-spacing: 0em;
    margin-top: 18rpx;
    color: #b1c2de;
}

.modal .modal-content .topTips .prize-content {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    padding-top: 94rpx;
    position: relative;
    width: 100%;
}
.modal .modal-content .topTips .prize-content text {
    font-family: Source Han Sans CN;
    font-size: 16px;
    font-weight: normal;
    text-align: center;
    letter-spacing: 0em;

    color: #ffffff;
}
.modal .modal-content .topTips .prize-content .prizeImage {
    height: 40rpx;
}
.modal .modal-content .topTips .prize-content .prizeImage1 {
    width: 110rpx;
    height: 80rpx;
    position: absolute;
    right: 70rpx;
    top: 24rpx;
}
.modal .modal-content .topTips .prize-content .prizeImage2 {
    width: 130rpx;
    height: 90rpx;
    position: absolute;
    left: 60rpx;
    top: 136rpx;
}
.modal .modal-content .topTips .prize-content .noprize-text {
    font-size: 16px;
    font-weight: normal;
    text-align: center;
    letter-spacing: 0em;
    margin-top: 18rpx;
    color: #b1c2de;
}
.modal .modal-content .bottomBtn {
    padding-bottom: 48rpx;
}
.modal .modal-content .bottomBtn button {
    background: linear-gradient(180deg, #ffd279 0%, #ffef5f 100%);
    box-shadow: inset 0px -5px 8px 0px rgba(203, 92, 0, 0.4);
    width: 154px;
    height: 40px;
    border-radius: 24px;
    font-family: Source Han Sans CN;
    font-size: 16px;
    font-weight: 600;
    letter-spacing: 0em;
    color: #c74509;
}
.modal .modal-content .bottomBtn.active {
    display: flex;
    flex-direction: row;
    flex-wrap: nowrap;
    justify-content: center;
    align-items: center;
    width: 100%;
    overflow: hidden;
}
.modal .modal-content .bottomBtn.active button {
    flex: 1;
    flex-shrink: 0;
}
.modal .modal-content .bottomBtn.active button:first-child {
    margin-right: 32rpx;
    margin-left: 40rpx;
    box-sizing: border-box;
    border: 1px solid #ffffff;
    background: transparent;
    box-shadow: unset;
    font-family: Source Han Sans CN;
    font-size: 16px;
    font-weight: 500;
    text-align: center;
    letter-spacing: 0em;

    color: #ffffff;
}
.modal .modal-content .bottomBtn.active button:last-child {
    margin-right: 40rpx;
}
</style>
